// 添加必要的导入语句
const express = require('express');
const path = require('path');
const fs = require('fs');

// 定义视频和图像目录常量
// Directory paths
const VIDEOS_DIR = '/data/videos';
const IMAGES_DIR = '/data/images';

const router = express.Router();

// 视频相关的API路由
function setupVideoRoutes(pool) {
  // 修改现有的视频API端点，增加重试逻辑
  router.get('/api/videos', async (req, res) => {
    console.log('接收到 /api/videos 请求');
    
    // 最多重试3次
    const maxRetries = 3;
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        console.log(`尝试连接数据库... (第 ${attempt} 次尝试)`);
        
        // 执行查询前先测试连接
        const client = await pool.connect();
        try {
          console.log('数据库连接成功');
          console.log('执行SQL查询: SELECT * FROM Videos ORDER BY created_at DESC');
          
          const sqlQuery = `SELECT v.id AS id,
            v.filename,
            v.start_time,
            v.duration_seconds,
            ca.point_name,
            ca.channel_number,
            v.objects,
            ARRAY(
                SELECT distinct(l.label_text)
                FROM unnest(v.object_types) AS obj_type
                INNER JOIN Labels l ON l.config_id = v.config_id AND l.label_id = obj_type
            ) AS object_labels
          FROM Videos v
          INNER JOIN Configs cc ON v.config_id = cc.id
          INNER JOIN Channels ch ON v.config_id = ch.config_id AND v.channel_id = ch.channel_id
          INNER JOIN Cameras ca ON ch.camera_id = ca.id
          ORDER BY v.start_time DESC`;
          
          const result = await client.query(sqlQuery);
          console.log(`查询结果: 共 ${result.rows.length} 条记录`);
          
          res.setHeader('Content-Type', 'application/json');
          res.status(200).json(result.rows);
          console.log('响应已发送');
          return; // 成功后退出循环
        } finally {
          client.release(); // 确保释放连接
        }
      } catch (error) {
        console.error(`查询数据库时发生错误 (第 ${attempt} 次尝试):`, error);
        
        // 如果是最后一次尝试，则返回错误
        if (attempt === maxRetries) {
          res.status(500).json({ error: '数据库连接失败，请稍后重试' });
        } else {
          // 否则等待一段时间后重试
          console.log(`2秒后重试...`);
          await new Promise(resolve => setTimeout(resolve, 2000));
        }
      }
    }
  });

  // 提供视频文件的端点
  router.get('/api/videos/:filename', (req, res) => {
    const { filename } = req.params;
    const videoPath = path.join(VIDEOS_DIR, filename);
    
    console.log('API request for video:', filename);

    // 设置适当的视频流头部
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET');
    res.header('Access-Control-Expose-Headers', 'Content-Length');
    res.header('Content-Type', 'video/mp4');
    
    if (fs.existsSync(videoPath)) {
      res.sendFile(videoPath);
    } else {
      res.status(404).json({ error: 'Video not found' });
    }
  });

  // 删除视频的端点
  router.delete('/api/videos/:id', async (req, res) => {
    const client = await pool.connect();
    let committed = false;
    try {
      await client.query('BEGIN');
      
      // 先获取文件路径
      const videoInfo = await client.query(
        'SELECT filename FROM Videos WHERE id = $1', 
        [req.params.id]
      );

      if (videoInfo.rows.length === 0) {
        return res.status(404).json({ error: 'Video not found' });
      }

      const video_filename = videoInfo.rows[0].filename;
      const video_filepath = path.join(VIDEOS_DIR, video_filename);
      const image_filename = video_filename.replace('.mp4', '.jpg');
      const image_filepath = path.join(IMAGES_DIR, image_filename);

      // 删除数据库记录
      await client.query('DELETE FROM Videos WHERE id = $1', [req.params.id]);

      // 文件删除逻辑
      const deleteFile = async (path) => {
        try {
          await fs.promises.unlink(path);
        } catch (err) {
          if (err.code !== 'ENOENT') throw err; // 忽略文件不存在的错误
        }
      };

      console.log(`Deleting video file: ${video_filepath}`);
      console.log(`Deleting image file: ${image_filepath}`);

      await Promise.all([
        deleteFile(video_filepath),
        deleteFile(image_filepath)
      ]);
      console.log(`Deleted video file: ${video_filepath}`);
      console.log(`Deleted image file: ${image_filepath}`);

      await client.query('COMMIT');
      committed = true;

      res.json({ 
        message: 'Video and associated files deleted successfully',
        deletedFiles: [video_filename, image_filename]
      });
    } catch (error) {
      if (!committed) {
        await client.query('ROLLBACK');
      }
      res.status(500).json({ 
        error: 'Deletion failed',
        details: error.message
      });
    } finally {
      client.release();
    }
  });

  // 关键：返回router对象
  return router;
}

module.exports = setupVideoRoutes;